"""
数据绑定系统核心实现
实现MVVM模式的数据绑定，支持单向和双向数据绑定
"""

class ObservableObject:
    """可观察对象基类，实现属性变更通知机制"""
    
    def __init__(self):
        self._properties = {}
        self._observers = {}
    
    def set_property(self, name, value):
        """设置属性值"""
        old_value = self._properties.get(name)
        self._properties[name] = value
        
        # 通知属性变更
        if old_value != value:
            self.notify_property_changed(name, old_value, value)
    
    def get_property(self, name):
        """获取属性值"""
        return self._properties.get(name)
    
    def notify_property_changed(self, name, old_value, new_value):
        """通知属性变更"""
        if name in self._observers:
            for callback in self._observers[name]:
                callback(name, old_value, new_value)
    
    def bind_property(self, name, callback):
        """绑定属性变更回调"""
        if name not in self._observers:
            self._observers[name] = []
        self._observers[name].append(callback)
    
    def unbind_property(self, name, callback=None):
        """解除属性绑定"""
        if name in self._observers:
            if callback:
                if callback in self._observers[name]:
                    self._observers[name].remove(callback)
            else:
                del self._observers[name]


class PropertyBinder:
    """属性绑定器，实现属性绑定逻辑"""
    
    def __init__(self):
        self._bindings = []
    
    def bind(self, source, source_property, target, target_property):
        """建立单向绑定"""
        def callback(name, old_value, new_value):
            setattr(target, target_property, new_value)
        
        source.bind_property(source_property, callback)
        # 立即同步一次
        setattr(target, target_property, source.get_property(source_property))
        
        binding = {
            'source': source,
            'source_property': source_property,
            'target': target,
            'target_property': target_property,
            'callback': callback
        }
        self._bindings.append(binding)
        return binding
    
    def bind_two_way(self, source, source_property, target, target_property):
        """建立双向绑定"""
        # source -> target
        def source_callback(name, old_value, new_value):
            setattr(target, target_property, new_value)
        
        source.bind_property(source_property, source_callback)
        
        # target -> source
        def target_callback(name, old_value, new_value):
            source.set_property(source_property, new_value)
        
        target.bind_property(target_property, target_callback)
        
        # 立即同步一次
        source_value = source.get_property(source_property)
        target_value = getattr(target, target_property, None)
        
        if source_value is not None:
            setattr(target, target_property, source_value)
        elif target_value is not None:
            source.set_property(source_property, target_value)
        
        binding = {
            'source': source,
            'source_property': source_property,
            'target': target,
            'target_property': target_property,
            'source_callback': source_callback,
            'target_callback': target_callback
        }
        self._bindings.append(binding)
        return binding
    
    def unbind(self, binding):
        """解除绑定"""
        if binding in self._bindings:
            self._bindings.remove(binding)
            
            if 'source_callback' in binding:
                binding['source'].unbind_property(binding['source_property'], binding['source_callback'])
            if 'target_callback' in binding:
                binding['target'].unbind_property(binding['target_property'], binding['target_callback'])
            if 'callback' in binding:
                binding['source'].unbind_property(binding['source_property'], binding['callback'])


class DataBindingEngine:
    """数据绑定引擎"""
    
    def __init__(self):
        self.binder = PropertyBinder()
        self._bindings = []
    
    def create_binding(self, source, source_property, target, target_property, two_way=False):
        """创建绑定"""
        if two_way:
            binding = self.binder.bind_two_way(source, source_property, target, target_property)
        else:
            binding = self.binder.bind(source, source_property, target, target_property)
        
        self._bindings.append(binding)
        return binding
    
    def remove_binding(self, binding):
        """移除绑定"""
        if binding in self._bindings:
            self._bindings.remove(binding)
            self.binder.unbind(binding)
    
    def clear_bindings(self):
        """清除所有绑定"""
        for binding in self._bindings[:]:
            self.remove_binding(binding)